package ee.videorentalstore.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class UserInputReader 
{	
	private static UserInputReader instance = null;
	private BufferedReader cmdInputReader = null;
	private final String EMPTY_STRING = "";
	
	
	private UserInputReader() 
	{
		initializeInputStream();	
	}
	
	
	public static UserInputReader getInstance()
	{
		if (instance == null)
		{
			instance = new UserInputReader();
		}
		return instance;
	}
	
	
	private void initializeInputStream()
	{
        cmdInputReader = new BufferedReader(
        		new InputStreamReader(
        				System.in));
	}
	
	
	public String readLine()
	{
		String inputLine = EMPTY_STRING;
		
		try 
		{
			inputLine = cmdInputReader.readLine();
		}
		catch (Exception e) 
		{
			System.err.println("ERROR in " + this.getClass().getName() + " readLine(). " +
					"Errormessage: " + e.getMessage() + ". Trying to reinitialize input stream.");
			initializeInputStream();
			System.out.println("Reinitializing input stream was successful");
		}
		
		return inputLine;
	}
	
	
	public void closeCmdInputStream()
	{
		try
		{
			if (cmdInputReader != null)
			{
				cmdInputReader.close();
			}
		}
		catch (IOException ioe)
		{
			System.err.println("ERROR in " + this.getClass().getName() + " closeCmdInputStream(): " + ioe.getMessage());
		}
	} 
}
